package com.apexsoft.assets.base.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.apexsoft.assets.base.PagedArrayList;
import com.apexsoft.assets.base.anotation.MapperParam;


import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

public class BeanMapUtil {
    public static <T> T Map2Bean(Map<String, ?> map, Class<T> clazz){
        if(map == null || map.isEmpty()){
            return null;
        }
        Field[] fields = clazz.getDeclaredFields();
        HashMap<String, String> mapping = CollUtil.newHashMap();
        for (Field field : fields){
            MapperParam mapperParam = field.getAnnotation(MapperParam.class);
            if(mapperParam != null){
                String key = mapperParam.value();
                mapping.put(key,field.getName());
            }
        }
        return BeanUtil.toBean(map, clazz, CopyOptions.create().setFieldMapping(mapping));
    }


    public static <T> PagedArrayList<T> Map2Bean(List<? extends Map<String, ?>> mapList, Class<T> clazz){
        if(mapList == null || mapList.isEmpty()){
            return null;
        }
        int total = mapList.size();
        if(mapList instanceof PagedArrayList){
            total = ((PagedArrayList<?>) mapList).getTotal();
        }
        Field[] fields = clazz.getDeclaredFields();
        HashMap<String, String> mapping = CollUtil.newHashMap();
        for (Field field : fields){
            MapperParam mapperParam = field.getAnnotation(MapperParam.class);
            if(mapperParam != null){
                String key = mapperParam.value();
                mapping.put(key,field.getName());
            }
        }
        return new PagedArrayList<>(mapList.stream().map(e -> BeanUtil.toBean(e, clazz, CopyOptions.create().setFieldMapping(mapping))).collect(toList()),total);
    }

    //将字段名转成数据库字段名
    public static String Sort2Field(String sort, Class clazz){
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields){
            MapperParam mapperParam = field.getAnnotation(MapperParam.class);
            if(mapperParam != null){
                String key = mapperParam.value();
                if(sort.equals(field.getName())){
                    sort = '"' + key + '"' ;
                }
            }
        }
        return sort;
    }
}
